package org.jeecg.modules.xindian.reconciliation.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.xindian.reconciliation.controller.req.UnCheckQuery;
import org.jeecg.modules.xindian.reconciliation.controller.rsp.UnCheckPolicyInfo;
import org.jeecg.modules.xindian.reconciliation.entity.*;
import org.jeecg.modules.xindian.reconciliation.enums.OtherSettlementFalg;
import org.jeecg.modules.xindian.reconciliation.enums.RelationType;
import org.jeecg.modules.xindian.reconciliation.mapper.PolicySettlementTypeStatisticsMapper;
import org.jeecg.modules.xindian.reconciliation.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.jeecg.modules.xindian.reconciliation.enums.RelationType.*;

/**
 * @Description: 结算类型汇总保单关联
 * @Author: jeecg-boot
 * @Date: 2024-06-24
 * @Version: V1.0
 */
@Service
@Slf4j
public class PolicySettlementTypeStatisticsServiceImpl extends ServiceImpl<PolicySettlementTypeStatisticsMapper, PolicySettlementTypeStatistics> implements IPolicySettlementTypeStatisticsService {
    @Autowired
    private IPolicySettlementStatisticsService policySettlementStatisticsService;
    @Autowired
    ISalesmanSettlementInfoService salesmanSettlementInfoService;
    @Autowired
    IChannelSettlementInfoService channelSettlementInfoService;
    @Autowired
    private IPolicyUnSettlementTypeStatisticsService policyUnSettlementTypeStatisticsService;
    @Autowired    private ICollisionObjectService collisionObjectService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    public static  final BigDecimal PREMIUM_TAX_POINT = BigDecimal.valueOf(1.06D);

    @Override
    public void process(List<PolicySettlementTypeStatistics> statistics, String id, String date, RelationType type) {
        Assert.notBlank(id, "结算汇总id不能未空");
        Assert.notNull(type, "结算汇总类型不能为空");
        //查询历史数据
        List<PolicySettlementTypeStatistics> processDate = new ArrayList<>();
        List<PolicySettlementTypeStatistics> oldData;
        //清理历史数据
        switch (type) {
            case INSURANCE: {
                //清理历史表
                oldData = lambdaQuery().eq(PolicySettlementTypeStatistics::getInsuranceSettlementId, id).eq(PolicySettlementTypeStatistics::getType,INSURANCE.name()).list();
                Map<String, PolicySettlementTypeStatistics> policySettlementStatisticsMap = oldData.stream().collect(Collectors.toMap(PolicySettlementTypeStatistics::getPolicyNo, Function.identity()));
                getBaseMapper().cleanInsuranceSettlementInfo(id);
                statistics.forEach(statistic -> {
                    PolicySettlementTypeStatistics formDb = policySettlementStatisticsMap.get(statistic.getPolicyNo());
                    if (formDb == null) {
                        processDate.add(statistic);
                    } else {
                        formDb.setInsuranceFee(statistic.getInsuranceFee());
                        formDb.setInsuranceFeeRate(statistic.getInsuranceFeeRate());
                        formDb.setInsuranceSettlementId(statistic.getInsuranceSettlementId());
                        processDate.add(formDb);
                    }
                });
            }
            break;
            case CHANNEL: {
                //查找保险公司的数据
                oldData = lambdaQuery().eq(PolicySettlementTypeStatistics::getType, INSURANCE.name()).eq(PolicySettlementTypeStatistics::getDate, date).list();
                Map<String, PolicySettlementTypeStatistics> policySettlementStatisticsMap = oldData.stream().collect(Collectors.toMap(PolicySettlementTypeStatistics::getPolicyNo, Function.identity()));
                getBaseMapper().deleteChannelSettlementInfo(id);
                statistics.forEach(statistic -> {
                    PolicySettlementTypeStatistics formDb = policySettlementStatisticsMap.get(statistic.getPolicyNo());
                    if (formDb == null) {
                        processDate.add(statistic);
                    } else {
                        statistic.setInsuranceFee(formDb.getInsuranceFee());
                        statistic.setInsuranceFeeRate(formDb.getInsuranceFeeRate());
                        statistic.setInsuranceSettlementId(formDb.getInsuranceSettlementId());
                        processDate.add(statistic);
                    }
                });
            }
            break;
            case SALESMAN: {
                oldData = lambdaQuery().eq(PolicySettlementTypeStatistics::getType, INSURANCE.name()).eq(PolicySettlementTypeStatistics::getDate, date).list();
                Map<String, PolicySettlementTypeStatistics> policySettlementStatisticsMap = oldData.stream().collect(Collectors.toMap(PolicySettlementTypeStatistics::getPolicyNo, Function.identity()));
                getBaseMapper().deleteSalesmanSettlementInfo(id);
                statistics.forEach(statistic -> {
                    PolicySettlementTypeStatistics formDb = policySettlementStatisticsMap.get(statistic.getPolicyNo());
                    if (formDb == null) {
                        processDate.add(statistic);
                    } else {
                        statistic.setInsuranceFee(formDb.getInsuranceFee());
                        statistic.setInsuranceFeeRate(formDb.getInsuranceFeeRate());
                        statistic.setInsuranceSettlementId(formDb.getInsuranceSettlementId());
                        statistic.setPayDate(formDb.getPayDate());
                        processDate.add(statistic);
                    }
                });
            }
            break;
        }
        this.saveOrUpdateBatch(processDate);
    }

    @Override
    public PolicySettlementTypeStatistics build(InsuranceStatistics insuranceStatistics, String settlementId, RelationType type, BigDecimal rate) {
        PolicySettlementTypeStatistics settlementStatistic = new PolicySettlementTypeStatistics();
        settlementStatistic.setType(type.name());
        settlementStatistic.setCost(insuranceStatistics.getCost());
        settlementStatistic.setKaiBiaoTime(insuranceStatistics.getKaiBiaoTime());
        settlementStatistic.setPlatform(insuranceStatistics.getPlatform());
        BigDecimal proxyRate = BigDecimal.ZERO;
        switch (insuranceStatistics.getPlatform()){
            case  "guangrun":{
                proxyRate = BigDecimal.valueOf(0.05);
                break;
            }
            case  "xierong":{
                proxyRate = BigDecimal.valueOf(0.03);
                break;
            }
            case  "zhonglian":{
                proxyRate = BigDecimal.valueOf(0.03);
                break;
            }
        }
        settlementStatistic.setProxyRate(proxyRate);
        settlementStatistic.setExTaxPremium(insuranceStatistics.getCost().divide(PREMIUM_TAX_POINT, RoundingMode.CEILING).setScale(2, RoundingMode.HALF_UP));
        //区分比例费用
//        anJi,HuZhou,安吉
//        changXin,HuZhou,长兴
//        deQing,HuZhou,德清
//        HangZhou,"",杭州
//        HuZhou,"",湖州市
//        JiaXin,"",嘉兴
//        LiShui,"",丽水
//        NingBo,"",宁波
//        QuZhou,"",衢州
//        TaiZhou,"",台州
//        ZhouSan,"",舟山
//        ZJSPT,"",浙江省平台
        BigDecimal systemRate = BigDecimal.valueOf(0.25);
        switch (insuranceStatistics.getArea()){
            case "JH-YiWu":{
                switch (insuranceStatistics.getInsuranceCompany()){
                    case "DJCX":{
                        systemRate  =  BigDecimal.valueOf(0.25);
                    }break;
                    case "YGBX":{
                        systemRate  =  BigDecimal.valueOf(0.25);
                    }break; default:{

                    }
                }
            };break;
            case "LiShui":{
                systemRate  =  BigDecimal.valueOf(0.15);
            };break;
            case "QuZhou":{
                if ("ZSBX".equals(insuranceStatistics.getInsuranceCompany())) {
                    systemRate = BigDecimal.valueOf(0.24);
                }
            };
            case "JinHua":{
                switch (insuranceStatistics.getInsuranceCompany()){
                    case "DJCX":{
                        systemRate  =  BigDecimal.valueOf(0.25);
                    }break;
                    case "YGBX":{
                        systemRate  =  BigDecimal.valueOf(0.2);
                    }break; default:{

                    }
                }
            };break;default:{

            }
        }
        settlementStatistic.setSystemRate(systemRate);
        //这个表示
        settlementStatistic.setSystemFee(settlementStatistic.getExTaxPremium().multiply(systemRate).divide(PREMIUM_TAX_POINT, RoundingMode.CEILING).setScale(2, RoundingMode.HALF_UP));
        switch (type) {
            case CHANNEL: {
                settlementStatistic.setChannelSettlementId(settlementId);
            }
            break;
            case SALESMAN: {
                settlementStatistic.setSalesmanFee(settlementStatistic.getExTaxPremium().multiply(rate).setScale(2, RoundingMode.HALF_UP));
                settlementStatistic.setSalesmanFeeRate(rate);
                settlementStatistic.setSalesmanSettlementId(settlementId);
                settlementStatistic.setOtherSettlementFalg(OtherSettlementFalg.N.name());
            }
            break;
            case INSURANCE: {
                settlementStatistic.setInsuranceFee(settlementStatistic.getExTaxPremium().multiply(rate).setScale(2, RoundingMode.HALF_UP));
                settlementStatistic.setOtherSettlementFalg(OtherSettlementFalg.N.name());
                settlementStatistic.setInsuranceFeeRate(rate);
                settlementStatistic.setInsuranceSettlementId(settlementId);
                settlementStatistic.setId(insuranceStatistics.getId());
            }
        }
        settlementStatistic.setApplyTime(insuranceStatistics.getApplyTime());
        settlementStatistic.setArea(insuranceStatistics.getArea());
        settlementStatistic.setChannelProvider(insuranceStatistics.getChannelProvider());
        settlementStatistic.setCost(insuranceStatistics.getCost());
        settlementStatistic.setInsuranceCompany(insuranceStatistics.getInsuranceCompany());
        settlementStatistic.setInsureActiveDate(insuranceStatistics.getInsureActiveDate());
        settlementStatistic.setInsuredName(insuranceStatistics.getInsuredName());
        settlementStatistic.setMargin(insuranceStatistics.getMargin());
        settlementStatistic.setOrderCreateTime(insuranceStatistics.getCreateTime());
        settlementStatistic.setOrderNo(insuranceStatistics.getOrderNo());
        settlementStatistic.setPayAccountName(insuranceStatistics.getPayAccountName());
        settlementStatistic.setPayState(insuranceStatistics.getPayState());
        settlementStatistic.setPayTime(insuranceStatistics.getPayTime());
        settlementStatistic.setPlatformCode(insuranceStatistics.getPlatformCode());
        settlementStatistic.setPolicyHolderName(insuranceStatistics.getPolicyHolderName());
        settlementStatistic.setPolicyNo(insuranceStatistics.getPolicyNo());
        settlementStatistic.setPolicyState(insuranceStatistics.getPolicyState());
        settlementStatistic.setProjectName(insuranceStatistics.getProjectName());
        settlementStatistic.setRate(insuranceStatistics.getRate());
        settlementStatistic.setSourceType(insuranceStatistics.getSourceType());
        BigDecimal insurancefee = ObjectUtil.isEmpty(settlementStatistic.getInsuranceFee())?BigDecimal.ZERO:settlementStatistic.getInsuranceFee().setScale(2, RoundingMode.HALF_UP);
        BigDecimal proxy = insurancefee.multiply(proxyRate);
        settlementStatistic.setProxyFee(proxy);
        return settlementStatistic;
    }

    @Override
    public PolicySettlementTypeStatistics queryByPolicyNo(String policyNo, String type) {
        return lambdaQuery().eq(PolicySettlementTypeStatistics::getPolicyNo, policyNo).eq(PolicySettlementTypeStatistics::getType, type).one();
    }

    @Override
    public Map<String, PolicySettlementTypeStatistics> queryByPolicyNos(List<String> policyNo) {
        if (CollectionUtil.isEmpty(policyNo)) {
            return new HashMap<>();
        }
        return lambdaQuery().in(PolicySettlementTypeStatistics::getPolicyNo, policyNo).eq(PolicySettlementTypeStatistics::getType, INSURANCE.name()).list().stream().collect(Collectors.toMap(PolicySettlementTypeStatistics::getPolicyNo, Function.identity()));
    }

    @Override
    public Page<UnCheckPolicyInfo> queryUnCheckInfo(Page page, UnCheckQuery policyInfo) {
        Page<UnCheckPolicyInfo> unCheckPolicyInfoPage = getBaseMapper().queryUncheckInfoList(page, policyInfo);
        processUncheckData(policyInfo, unCheckPolicyInfoPage.getRecords());
        return unCheckPolicyInfoPage;
    }

    private void processUncheckData(UnCheckQuery policyInfo, List<UnCheckPolicyInfo> unCheckPolicyInfoPage) {
        List<String> ps = unCheckPolicyInfoPage.stream().map(UnCheckPolicyInfo::getPolicyNo).collect(Collectors.toList());
        Map<String, List<PolicySettlementTypeStatistics>> pts = queryByDateAndPolicyNo(policyInfo.getDate(), ps).stream().collect(Collectors.groupingBy(PolicySettlementTypeStatistics::getPolicyNo));
        unCheckPolicyInfoPage.forEach(rd -> {
            List<PolicySettlementTypeStatistics> pls = pts.get(rd.getPolicyNo());
            List<String> types = new ArrayList<>();
            List<UnCheckPolicyInfo.UnCheckOptions> unCheckOptions = pls.stream().map(pt -> {
                UnCheckPolicyInfo.UnCheckOptions options = new UnCheckPolicyInfo.UnCheckOptions();
                RelationType type = RelationType.valueOf(pt.getType());
                options.setValue(pt.getId());
                switch (type) {
                    case CHANNEL: {
                        options.setLabel(pt.getChannelName());
                        types.add(pt.getChannelName());

                    }
                    break;
                    case SALESMAN: {
                        options.setLabel(pt.getSalesmanName());
                        types.add(pt.getSalesmanName());
                    }
                    break;
                    default:
                        break;
                }
                return options;
            }).collect(Collectors.toList());
            rd.setUnCheckInfo(org.springframework.util.StringUtils.collectionToCommaDelimitedString(types));
            rd.setUnCheckList(unCheckOptions);
        });
    }

    @Override
    public List<UnCheckPolicyInfo> queryUnCheckInfoList(UnCheckQuery query) {
        List<UnCheckPolicyInfo> unCheckPolicyInfoPage = getBaseMapper().queryUncheckInfoListNoPage(query);
        processUncheckData(query, unCheckPolicyInfoPage);
        return unCheckPolicyInfoPage;
    }

    @Override
    public List<PolicySettlementTypeStatistics> queryByDateAndPolicyNo(String date, List<String> policyNos) {
        if (CollectionUtil.isEmpty(policyNos)) {
            return new ArrayList<>();
        }
        List<String> types = Arrays.asList(RelationType.CHANNEL.name(), RelationType.SALESMAN.name());
        LambdaQueryChainWrapper<PolicySettlementTypeStatistics> query = lambdaQuery();
        if (StringUtils.isNotBlank(date)) {
            query.eq(PolicySettlementTypeStatistics::getDate, date);
        }
        return query.in(PolicySettlementTypeStatistics::getPolicyNo, policyNos).in(PolicySettlementTypeStatistics::getType, types).list();
    }

    @Override
    public void selectCheck(String id) {
        PolicySettlementTypeStatistics type = getById(id);
        //查询状态的数据列表
        List<PolicySettlementTypeStatistics> process  = lambdaQuery()
                .eq(PolicySettlementTypeStatistics::getPolicyNo,type.getPolicyNo()).in(PolicySettlementTypeStatistics::getType,Arrays.asList(CHANNEL.name(),SALESMAN.name()))
                .eq(PolicySettlementTypeStatistics::getOtherSettlementFalg,OtherSettlementFalg.N.name())
                .list();
        List<String> objectInfo = new ArrayList<>();
        process.forEach(pt->{
            RelationType dapt  = RelationType.valueOf(pt.getType());
            switch (dapt ) {
                case CHANNEL: {
                    objectInfo.add(pt.getChannelName());
                } break;
                case SALESMAN: {
                    objectInfo.add(pt.getSalesmanName());
                }
                break;
                default:
                    break;
            }
        });

        CollisionObject object = new CollisionObject();
        RelationType types  = RelationType.valueOf(type.getType());
        switch (types){
            case CHANNEL: {
                object.setAttribution(type.getChannelName());
            } break;
            case SALESMAN: {
                object.setAttribution(type.getSalesmanName());
            }
            break;
            default:
                break;
        }
        BeanUtils.copyProperties(type,object);
        object.setCollisionObject(org.springframework.util.StringUtils.collectionToCommaDelimitedString(objectInfo));
        transactionTemplate.execute(status -> {
            collisionObjectService.save(object);
            getBaseMapper().cleanUnCheckInfo(id, type.getPolicyNo());
            return null;
        });
    }

    @Override
    public void processPolicySettlement(String date) {
        //判断订单是否存在
        Assert.notBlank(date,"请选择要初始化的月份");
        Long totalPr  =  policySettlementStatisticsService.lambdaQuery().eq(PolicySettlementStatistics::getDate, date).count();
        Assert.isTrue(0 == totalPr, "周期{}的数据已生成,请勿重新执行", date);
        Integer total = getBaseMapper().queryUncheckTotal(date);
        total = total==null?0:total;
        Assert.isTrue(0 == total, "请先处理{}周期下的撞单数据", date);
        List<SalesmanSettlementInfo> settlementInfo = salesmanSettlementInfoService.lambdaQuery().eq(SalesmanSettlementInfo::getDate, date).list();
        Assert.notEmpty(settlementInfo, "请先初始化业务员{}周期数据", date);
        List<ChannelSettlementInfo> channelSettlementInfos = channelSettlementInfoService.lambdaQuery().eq(ChannelSettlementInfo::getDate, date).list();
        Assert.notEmpty(channelSettlementInfos, "请先初始渠道商{}周期数据", date);
        //查询周期下的订单数据
        List<String> channelSalesmanTypes = Arrays.asList(RelationType.CHANNEL.name(), RelationType.SALESMAN.name());
        List<String> insuranceType = Arrays.asList(RelationType.INSURANCE.name());


        //保险公司当月数据
        LambdaQueryChainWrapper<PolicySettlementTypeStatistics> insuranceQuery = lambdaQuery();
        insuranceQuery.eq(PolicySettlementTypeStatistics::getDate, date);
        List<PolicySettlementTypeStatistics> insuranceStatistics = insuranceQuery.in(PolicySettlementTypeStatistics::getType, insuranceType).list();

        //渠道商和业务员当月数据
        LambdaQueryChainWrapper<PolicySettlementTypeStatistics> query = lambdaQuery();
        query.eq(PolicySettlementTypeStatistics::getDate, date);
        List<PolicySettlementTypeStatistics> channelSalesmanStatistics = query.in(PolicySettlementTypeStatistics::getType, channelSalesmanTypes).list();

        List<String> insurancePolicyNos=  insuranceStatistics.stream().map(PolicySettlementTypeStatistics::getPolicyNo).collect(Collectors.toList());
        List<String> policyNos=  channelSalesmanStatistics.stream().map(PolicySettlementTypeStatistics::getPolicyNo).collect(Collectors.toList());
        Map<String,List<PolicySettlementTypeStatistics>> channelSalesmanMaps =  channelSalesmanStatistics.stream().collect(Collectors.groupingBy(PolicySettlementTypeStatistics::getPolicyNo));
        Map<String,PolicySettlementTypeStatistics> insuranceMaps = insuranceStatistics.stream().collect(Collectors.toMap(PolicySettlementTypeStatistics::getPolicyNo,Function.identity()));
        List<PolicySettlementStatistics> policySettlementStatistics = new ArrayList<>();
        insuranceMaps.keySet().forEach(key->{
            //获取渠道
            List<PolicySettlementTypeStatistics> policySettlementTypeStatistics  = channelSalesmanMaps.get(key);
            PolicySettlementStatistics settlementStatistics = new PolicySettlementStatistics();
            PolicySettlementTypeStatistics typeStatistics = insuranceMaps.get(key);
            BeanUtils.copyProperties(typeStatistics,settlementStatistics);
            if(CollectionUtils.isNotEmpty(policySettlementTypeStatistics)){
                policySettlementTypeStatistics.forEach(one->{
                    RelationType  type = RelationType.valueOf(one.getType());
                    switch (type){
                        case CHANNEL:{
                            settlementStatistics.setChannelSettlementId(one.getChannelSettlementId());
                            settlementStatistics.setPayDate(one.getDate());
                            if(OtherSettlementFalg.N.name().equals(one.getOtherSettlementFalg())){
                                settlementStatistics.setChannelFeeRate(one.getChannelFeeRate());
                                settlementStatistics.setChannelFee(one.getChannelFee());
                                settlementStatistics.setChannelProvider(one.getChannelProvider());
                                settlementStatistics.setChannelName(one.getChannelName());
                            }else{
                                settlementStatistics.setChannelAloneFee(one.getChannelAloneFee());
                                settlementStatistics.setChannelAloneRate(one.getChannelAloneRate());
                                settlementStatistics.setChannelAloneName(one.getChannelAloneName());
                                settlementStatistics.setOtherSettlementFalg(OtherSettlementFalg.Y.name());
                            }
                        }break;
                        case SALESMAN:{
                            settlementStatistics.setSalesmanFee(one.getSalesmanFee());
                            settlementStatistics.setSalesmanFeeRate(one.getSalesmanFeeRate());
                            settlementStatistics.setSalesmanId(one.getSalesmanId());
                            settlementStatistics.setSalesmanName(one.getSalesmanName());
                            settlementStatistics.setSalesmanSettlementId(one.getSalesmanSettlementId());
                            settlementStatistics.setPayDate(one.getDate());
                        }
                    }
                });
            }
            policySettlementStatistics.add(settlementStatistics);
        });
        List<PolicyUnSettlementTypeStatistics> neeDAdd = new ArrayList<>();
        //处理没有在里面的保单
        policyNos.removeAll(insurancePolicyNos);
        List<String> unSettlementType = policyUnSettlementTypeStatisticsService.list().stream().map(PolicyUnSettlementTypeStatistics::getId).collect(Collectors.toList());
        new HashSet<>(policyNos).forEach(one->{
            //登记为记录的保单
            List<PolicySettlementTypeStatistics>  un =  channelSalesmanMaps.get(one);
            List<PolicyUnSettlementTypeStatistics> tags =    un.stream().filter(dt-> !unSettlementType.contains(dt.getId())).map(unOne->{
                PolicyUnSettlementTypeStatistics tag = new PolicyUnSettlementTypeStatistics();
                BeanUtils.copyProperties(unOne,tag);
                return tag;
            }).collect(Collectors.toList());
            neeDAdd.addAll(tags);
        });

        transactionTemplate.execute(status -> {
            //添加新数据
            policySettlementStatisticsService.saveBatch(policySettlementStatistics);
            if(CollectionUtils.isNotEmpty(neeDAdd)){
                policyUnSettlementTypeStatisticsService.saveBatch(neeDAdd);
            }
            //开始处理未到期的账单信息//处理未到期的账单信息
            List<PolicyUnSettlementTypeStatistics> unSettlementFromDb =   policyUnSettlementTypeStatisticsService.list();
            Map<String,List<PolicyUnSettlementTypeStatistics>>   unSettlementMap =  unSettlementFromDb.stream().collect(Collectors.groupingBy(PolicyUnSettlementTypeStatistics::getPolicyNo));
            //查询未到期的账单在数据库中的值
            List<String> unSettlementPolicyNo =  unSettlementFromDb.stream().map(PolicyUnSettlementTypeStatistics::getPolicyNo).collect(Collectors.toList());
            List<PolicySettlementStatistics>  insuranceHistory = CollectionUtils.isEmpty(unSettlementPolicyNo)?new ArrayList<>(): policySettlementStatisticsService.lambdaQuery().in(PolicySettlementStatistics::getPolicyNo,unSettlementPolicyNo).list();
            List<PolicySettlementStatistics> updateInsuranceHistory = new ArrayList<>();
            List<String> deleteIds = new ArrayList<>();
            Map<String,PolicySettlementStatistics>   insuranceHistoryMaps =  insuranceHistory.stream().collect(Collectors.toMap(PolicySettlementStatistics::getPolicyNo,Function.identity()));
            insuranceHistoryMaps.keySet().forEach(key->{
                List<PolicyUnSettlementTypeStatistics> policySettlementTypeStatistics  = unSettlementMap.get(key);
                PolicySettlementStatistics typeStatistics = insuranceHistoryMaps.get(key);
                //TODO 因为开标时间账单周期不一致来处理这些数据
                if(typeStatistics == null){
                    log.warn("保单{}未在保司周期数据中找到,可能因为按照开标时间算导致的",typeStatistics.getPolicyNo());
                }else {
                    policySettlementTypeStatistics.forEach(one->{
                        deleteIds.add(one.getId());
                        RelationType  type = RelationType.valueOf(one.getType());
                        //先清理历史数据,然后根据新数据处理
                        typeStatistics.setSalesmanFee(BigDecimal.ZERO);
                        typeStatistics.setSalesmanFeeRate(BigDecimal.ZERO);
                        typeStatistics.setSalesmanId("");
                        typeStatistics.setSalesmanName("");
                        typeStatistics.setSalesmanSettlementId("");
                        typeStatistics.setChannelFeeRate(BigDecimal.ZERO);
                        typeStatistics.setChannelFee(BigDecimal.ZERO);
                        typeStatistics.setChannelProvider("");
                        typeStatistics.setChannelName("");
                        switch (type){
                            case CHANNEL:{
                                typeStatistics.setChannelSettlementId(one.getChannelSettlementId());
                                typeStatistics.setPayDate(one.getDate());
                                if(OtherSettlementFalg.N.name().equals(one.getOtherSettlementFalg())){
                                    typeStatistics.setChannelFeeRate(one.getChannelFeeRate());
                                    typeStatistics.setChannelFee(one.getChannelFee());
                                    typeStatistics.setChannelProvider(one.getChannelProvider());
                                    typeStatistics.setChannelName(one.getChannelName());
                                }else{
                                    typeStatistics.setChannelAloneFee(one.getChannelAloneFee());
                                    typeStatistics.setChannelAloneRate(one.getChannelAloneRate());
                                    typeStatistics.setChannelAloneName(one.getChannelAloneName());
                                    typeStatistics.setOtherSettlementFalg(OtherSettlementFalg.Y.name());
                                }
                            }break;
                            case SALESMAN:{
                                typeStatistics.setSalesmanFee(one.getSalesmanFee());
                                typeStatistics.setSalesmanFeeRate(one.getSalesmanFeeRate());
                                typeStatistics.setSalesmanId(one.getSalesmanId());
                                typeStatistics.setSalesmanName(one.getSalesmanName());
                                typeStatistics.setSalesmanSettlementId(one.getSalesmanSettlementId());
                                typeStatistics.setPayDate(one.getDate());
                            }
                        }
                        updateInsuranceHistory.add(typeStatistics);
                    });
                }
            });

            if(CollectionUtils.isNotEmpty(updateInsuranceHistory)){
                policySettlementStatisticsService.updateBatchById(updateInsuranceHistory);
            }

            if(CollectionUtils.isNotEmpty(deleteIds)){
                policyUnSettlementTypeStatisticsService.removeByIds(deleteIds);
            }
            //删除数据
            return null;
        });
    }
}
